package cn.com.utt.gateway.security;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import cn.com.utt.common.log.SaveIpaddress;
import cn.com.utt.common.mapper.LockIpMapper;
import cn.com.utt.common.service.UserService;
import cn.com.utt.common.util.LocaleMessageSourceUtil;
import cn.com.utt.common.util.Tips;
import cn.com.utt.common.vo.LockIp;
import cn.com.utt.common.vo.User;
import cn.com.utt.unms.pojo.Log;
import cn.com.utt.unms.service.LogService;

public class CustomDaoAuthenticationProvider extends DaoAuthenticationProvider {
	
	@Autowired
    private UserService userService;
    @Autowired
	private LogService logService;
    
    @Autowired
	private LockIpMapper lockIpMapper;
    
    @Autowired
    private LocaleMessageSourceUtil messageSourceUtil;
	
	@Override  
	protected void additionalAuthenticationChecks(UserDetails userDetails,
			UsernamePasswordAuthenticationToken authentication)
			throws AuthenticationException {
		User user = (User)userDetails;
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			super.additionalAuthenticationChecks(userDetails, authentication);
			user.setFailtimes((short)0);
			try {
				user.setLastlogin(df.parse(df.format(new Date())));
				Date date = new Date();
				Log log = new Log();
				String ipaddress = SaveIpaddress.getThreadLocal()
						.get();
				log.setIpaddress(ipaddress);
				log.setUserId(user.getId());
				log.setContent(messageSourceUtil.getMessage(Tips.LogLogin)+ipaddress);
				log.setDate(date);
				log.setState(0);
				logService.save(log);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			user.setFailtimes((short)0);
			userService.update(user);
			if (user.getDomain().equals("cloud.anphat.vn")){
				String ipaddress = SaveIpaddress.getThreadLocal().get();
				lockIpMapper.deleteByIp(ipaddress);
			}
		} catch (AuthenticationException exception) {
			if (user.getDomain().equals("cloud.anphat.vn")){
				String ipaddress = SaveIpaddress.getThreadLocal().get();
				LockIp lockIp = lockIpMapper.queryByIp(ipaddress);
				byte failtimes = 0;
				if (lockIp == null){
					failtimes++;
					lockIpMapper.save(ipaddress, (byte)1);
				}else{
					failtimes = lockIp.getFailtimes();
					failtimes++;
					lockIp.setFailtimes(failtimes);
					lockIpMapper.update(ipaddress, failtimes);
					if(failtimes == 5){
						throw new BadCredentialsException(messageSourceUtil.getMessage(Tips.LockIp).replaceAll("#", ipaddress).replaceAll("\\*", df.format(new Date().getTime() + 600000)));
					}
				}
				throw new BadCredentialsException(messageSourceUtil.getMessage(Tips.WrongPasswdVn).replace('#', (char)((5 - failtimes)+'0')));
			}else{
				//捕捉密码错误异常,错误次数加1
				short failtimes = user.getFailtimes();
				failtimes++;
				user.setFailtimes(failtimes);
				Date lastfail;
				try {
					lastfail = df.parse(df.format(new Date()));
				} catch (ParseException e) {
					throw exception;
				}
				user.setLastfail(lastfail);
				userService.update(user);
				if(failtimes == 5){
		    			throw new LockedException(messageSourceUtil.getMessage(Tips.LockAccount));
				}
				throw new BadCredentialsException(messageSourceUtil.getMessage(Tips.WrongPasswd).replace('#', (char)((5 - failtimes)+'0')));
			}
		}
	}

}
